package com.wanmait.schedule.interceptor;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wanmait.schedule.entity.Notice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/webSocket/{id}")
public class WebSocketServer {

    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 记录当前在线连接数
     */
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    //发送消息
    public void sendMessage(String message, List<String> sessionKey) throws IOException {

        for (String item:sessionKey){

            for (Object key:sessionMap.keySet()){

                if(item.equals(key)){
                    Session session=sessionMap.get(key);
                    if (session!=null){
                        System.out.println(session);
                        session.getBasicRemote().sendText(message);
                    }
                }
            }
        }
    }

    //用户登录建立连接进入方法
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        System.out.println(id);
        sessionMap.put(id, session);
        log.info("有新用户加入，userId={}, 当前在线人数为：{}", id, sessionMap.size());
    }
//
//    /**
//     * 连接关闭调用的方法
//     */
    @OnClose
    public void onClose(Session session, @PathParam("id") String id) {
        sessionMap.remove(id);
        log.info("有一连接关闭，移除userId={}的用户session, 当前在线人数为：{}", id, sessionMap.size());
    }
}
